<template>
  <div class="scroll-animation">
    <h1 class="scroll-btn" @click="add">add{{ isSelectListIndex }}</h1>
    <div
      class="card"
      :class="
        isSelectListIndex !== null && isSelectListIndex >= index ? 'show' : index % 2 ? 'leftT' : 'rightT'
      "
      v-for="(item, index) of list"
      :key="index"
    >
      {{ item.label }}
    </div>
  </div>
</template>

<script>
const defaultObj = {
  label: "Content",
};
export default {
  data() {
    return {
      list: [],
      isSelectListIndex: null,
      dom: null,
      clientHeight: 0,
    };
  },
  methods: {
    add() {
      this.list.push({ ...defaultObj });
      this.$nextTick(() => {
        this.scroll();
      });
    },
    scroll() {
      let doms = document.querySelectorAll(".card");
      let result = 0;
      for (let i = 0; i < doms.length; i++) {
        if (doms[i].getBoundingClientRect().top <= this.clientHeight) {
          result = i;
        }
      }
      this.isSelectListIndex = result;
    },
  },
  mounted() {
    this.dom = document.getElementsByClassName("scroll-animation")[0];
    this.clientHeight = this.dom.clientHeight;
    console.log(this.clientHeight);
    this.dom.addEventListener("scroll", this.scroll.bind(this));
    this.scroll();
  },
};
</script>

<style lang="scss" scoped>
.scroll-animation {
  width: 100%;
  height: 100%;
  text-align: center;
  background: #efedd6;
  overflow: hidden;
  overflow-y: auto;
  .scroll-btn {
    background: #fff;
    opacity: 0.6;
    cursor: pointer;
    position: sticky;
    top: 0;
    z-index: 1;
  }
  .card {
    margin: 0 auto;
    background-color: rgb(70, 130, 180);
    color: rgb(255, 255, 255);
    margin-top: 20px;
    border-radius: 30px;
    width: 400px;
    height: 200px;
    font-size: 45px;
    font-weight: bold;
    line-height: 200px;
    text-align: center;

    transition: transform 0.5s;
    &.show {
      transform: translateX(0);
    }
    &.leftT {
      transform: translateX(-400%);
    }
    &.rightT {
      transform: translateX(400%);
    }
  }
}
</style>